<?php

class InstrucoesController extends Zend_Controller_Action
{
	/**
	 * @var Model_InstrucoesSql $instrucoes Model_InstrucoesSql
	 */
    private $instrucoes;
    /**
     * 
     * @var Form_CadastroSql $form Form_CadastroSql
     */
    private $form;
    
    public function init()
    {
        $this->instrucoes = new Model_InstrucoesSql();
        
    }
    public function indexAction()
    {
        $this->view->instrucoes = $this->instrucoes->fetchAll(null,array("codigo_sistema","descritivo"));
    }

    public function newAction()
    {
        $this->form = new Form_CadastroSql();
        if ($this->getRequest ()->isPost ()) {
            $formData = $this->getRequest ()->getPost ();
            if ($this->form->isValid ( $formData )) {
                $this->save($formData);
                $this->_redirect('/instrucoes');
            }else{
        	   $this->form->populate($formData);
            }
        }
        
                
        $this->view->form = $this->form;
        $this->render('edit');
    }

    public function editAction()
    {
    	$codigo = $this->_getParam('codigo');
        $instrucao =  $this->instrucoes->fetchRow('codigo='.$codigo);
        
        $this->form = new Form_CadastroSql();
        
        if ($this->getRequest ()->isPost ()) {
            $formData = $this->getRequest ()->getPost ();
            if ($this->form->isValid ( $formData )) {
                $this->save($formData);
                $this->_redirect('/instrucoes');
            }
        }
        
        $this->form->populate($instrucao->toArray());
        $this->view->form = $this->form;
    }
	
	private function save($formData) {
		$instrucao=false;
		$dados = $this->form->getDados ();
		unset($dados['codigo']);
		if($this->form->getValue ( 'codigo' )){
		  $instrucao = $this->instrucoes->fetchRow ( "codigo=" . $this->form->getValue ( 'codigo' ) );
		}
		if ($instrucao) {
			$this->instrucoes->update ( $dados, "codigo=" . $this->form->getValue ( 'codigo' ) );
		} else {
			$this->instrucoes->insert ( $dados );
		}
	}
}





